﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Http;
using System.Configuration;

namespace ERPStore.Tasks.Monitor
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			uxDataGridView.AutoGenerateColumns = false;
			uxDataGridView.DataSource = uxTaskEntryListBindingSource;

			var settings = new ViewModels.SettingsViewModel();
			uxSettingsBindingSource.DataSource = settings;

			uxAddressTextBox.DataBindings.Add("Text", uxSettingsBindingSource, "Address", true, DataSourceUpdateMode.OnPropertyChanged);
			uxApiKeyTextBox.DataBindings.Add("Text", uxSettingsBindingSource, "ApiKey", true, DataSourceUpdateMode.OnPropertyChanged);
		}

		protected override void OnClosed(EventArgs e)
		{
			var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap
			{
				ExeConfigFilename = base.GetType().Assembly.Location + ".config"
			}, ConfigurationUserLevel.None);

			if (config.AppSettings.Settings.AllKeys.Any((i) => i.Equals("address", StringComparison.InvariantCultureIgnoreCase)))
			{
				config.AppSettings.Settings["address"].Value = uxAddressTextBox.Text;
			}
			else
			{
				config.AppSettings.Settings.Add("address", uxAddressTextBox.Text);
			}

			if (config.AppSettings.Settings.AllKeys.Any((i) => i.Equals("apiKey")))
			{
				config.AppSettings.Settings["apiKey"].Value = uxApiKeyTextBox.Text;
			}
			else
			{
				config.AppSettings.Settings.Add("apiKey", uxApiKeyTextBox.Text);
			}

			config.Save(ConfigurationSaveMode.Minimal);

			base.OnClosed(e);
		}


		private void uxStartButton_Click(object sender, EventArgs e)
		{
			var url = uxAddressTextBox.Text;
			using (var httpClient = new HttpClient())
			{
				httpClient.DefaultRequestHeaders.Add("ApiKey", uxApiKeyTextBox.Text);

				url = url + "/GetList";
				string content = null;
				var task = httpClient.GetStringAsync(url).ContinueWith((response) =>
					{
						content = response.Result;
					}).Wait(30 * 1000);

				if (content != null)
				{
					uxTaskEntryListBindingSource.DataSource = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ERPStore.Models.TaskEntry>>(content);
				}
			}
		}


	}
}
